<script setup lang="ts">
import type { FormInstance } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import { DictApi } from '@/apis'
import { useConfirm, useForm } from '@/hooks'
import * as Regexp from '@/utils/regexp'

const emit = defineEmits<{
  (e: 'change'): void
}>()

const visible = ref(false)
const loading = ref(false)
const readonly = ref(true)

const dataId = ref('')
const dataDetail = ref<DictApi.DictItemDetailResp>()

const isCreateMode = computed(() => dataId.value === '')
const title = computed(() => (isCreateMode.value ? '创建字典项' : '修改字典项'))

const formRef = ref<FormInstance>()

const { form, resetForm } = useForm({
  dictId: null,
  label: null,
  value: null,
  color: null,
  sort: 999,
  status: 1,
  description: null,
})

const rules: FormInstance['rules'] = {
  label: [{ required: true, match: Regexp.Name, message: '名称只能含有中文、数字、英文、下划线、短横线,长度为2-32位' }],
  value: [{ required: true, match: Regexp.Code, message: '编码只能含有英文、数字、下划线、短横线,以字母开头,长度为2-32位' }],
  // color: [{ required: false, match: Regexp.ColorRegex, message: '请输入正确的RGB颜色格式' }],
}

// 查询详情
const getDataDetail = async () => {
  dataDetail.value = await DictApi.getDictItemDetail(dataId.value)
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  loading.value = false
}

// 打开详情
const open = async (id: string) => {
  dataId.value = id
  loading.value = true
  visible.value = true
  readonly.value = true
  getDataDetail()
}

// 打开编辑
const edit = async (id: string) => {
  dataId.value = id
  loading.value = true
  visible.value = true
  readonly.value = false
  getDataDetail()
}

// 打开新增
const create = async (dictId: string) => {
  dataId.value = ''
  loading.value = false
  visible.value = true
  readonly.value = false

  form.dictId = dictId
}

// 保存
const onSave = async () => {
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) {
    return false
  }
  if (isCreateMode.value) {
    await DictApi.createDictItem(form)
    Message.success('添加成功')
  } else {
    await DictApi.updateDictItem(form, dataId.value)
    Message.success('修改成功')
  }
  emit('change')
  visible.value = false
  return true
}

// 取消
const onCancel = () => {
  readonly.value = true
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  formRef.value?.clearValidate()
}

// 编辑
const onEdit = () => {
  readonly.value = false
}

// 删除
const onDelete = () => {
  useConfirm(() => DictApi.removeDictItem(dataId.value), () => {
    emit('change')
    visible.value = false
  })
}

// 重置
const reset = () => {
  formRef.value?.resetFields()
  resetForm()
}

// 颜色选择控制
const supportColor = computed(() => {
  return form.color !== '' && form.color != null
})

const onColorSupport = (support) => {
  if (support) {
    form.color = '#165DFF'
  } else {
    form.color = ''
  }
}

defineExpose({ open, edit, create })
</script>

<template>
  <ProFormPanel
    v-model:visible="visible"
    mode="modal"
    :title="title"
    :loading="loading"
    :footer="isCreateMode"
    @confirm="onSave"
    @close="reset"
  >
    <a-form ref="formRef" layout="vertical" :model="form" :rules :readonly>
      <a-card title="基础信息" class="section">
        <template #extra>
          <ReadonlyEditButton
            v-if="!isCreateMode"
            :readonly="readonly"
            :deleteable="false"
            @edit="onEdit"
            @cancel="onCancel"
            @save="onSave"
            @delete="onDelete"
          />
        </template>
      </a-card>
      <a-row :gutter="28">
        <readonly-form-item label="字典标签(label)" field="label" tooltip="用于显示">
          <a-input v-model.trim="form.label" placeholder="请输入字典标签" />
        </readonly-form-item>
        <readonly-form-item label="字典值(code)" field="value" tooltip="用于编码">
          <a-input v-model.trim="form.value" placeholder="字典值" :disabled="!isCreateMode" />
        </readonly-form-item>
        <readonly-form-item label="颜色" field="color">
          <!-- <a-input v-model.trim="form.color" placeholder="请输入颜色" /> -->
          <a-space>
            <a-switch :default-checked="supportColor" checked-text="开启" unchecked-text="禁用" type="line" @change="onColorSupport" />
            <a-color-picker v-if="form.color" v-model="form.color" default-value="#165DFF" show-text disabled-alpha />
          </a-space>
        </readonly-form-item>
        <readonly-form-item label="状态" field="status">
          <DictSelect v-model="form.status" code="CommonStatusEnum" type="switch" />
          <template #readonly>
            <CellStatus :status="dataDetail?.status" />
          </template>
        </readonly-form-item>
        <readonly-form-item label="描述" field="description" :span="24">
          <a-textarea v-model.trim="form.description" placeholder="请输入描述" :max-length="255" show-word-limit />
        </readonly-form-item>
      </a-row>
    </a-form>
  </ProFormPanel>
</template>

<style lang="less" scoped></style>
